﻿using System;
using System.Windows.Media;

namespace Silverlight.Media.Encoder.Sinks
{
    public class AudioSampleSink : AudioSink
    {
        public event EventHandler<AudioFormatChangedArgs> AudioFormatChanged;

        public event EventHandler<OnSampleArgs> OnMediaSample;

        public event EventHandler OnCaptureStart;

        public event EventHandler OnCaptureStop;

        #region Invokers
        private void InvokeOnCaptureStart()
        {
            var e = new EventArgs();
            EventHandler handler = OnCaptureStart;
            if (handler != null) handler(this, e);
        }

        private void InvokeOnCaptureStop()
        {
            var e = new EventArgs();
            EventHandler handler = OnCaptureStop;
            if (handler != null) handler(this, e);
        }

        private void InvokeOnMediaSample(OnSampleArgs e)
        {
            EventHandler<OnSampleArgs> handler = OnMediaSample;
            if (handler != null) handler(this, e);
        }

        private void InvokeAudioFormatChanged(AudioFormatChangedArgs e)
        {
            var handler = AudioFormatChanged;
            if (handler != null) handler(this, e);
        }
        #endregion

        protected override void OnCaptureStarted()
        {
            InvokeOnCaptureStart();
        }

        protected override void OnCaptureStopped()
        {
            InvokeOnCaptureStop();
        }

        protected override void OnFormatChange(AudioFormat audioFormat)
        {
            InvokeAudioFormatChanged(new AudioFormatChangedArgs(audioFormat));
        }

        protected override void OnSamples(long sampleTime, long sampleDuration, byte[] sampleData)
        {
            InvokeOnMediaSample(new OnSampleArgs(sampleTime, sampleDuration, sampleData, SampleType.Audio));
        }
    }
}
